package org.pine.dictionary.service;

import cn.hutool.core.bean.BeanUtil;
import org.pine.dictionary.bean.PageRequest;
import org.pine.dictionary.bean.excel.DictionaryImportDto;
import org.pine.dictionary.bean.request.DictionaryQueryRequest;
import org.pine.dictionary.bean.request.DictionarySaveRequest;
import org.pine.dictionary.bean.response.DictionaryQueryResponse;
import org.pine.dictionary.service.bo.DictionaryBo;
import org.pine.dictionary.service.query.DictionaryQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 字典表 服务类
 * </p>
 *
 * @author pine
 * @since 2024-05-15
 */
@Transactional(rollbackFor = Exception.class)
public interface IDictionaryService extends BaseService<String, DictionaryBo, DictionaryQuery, DictionarySaveRequest, DictionaryQueryRequest, DictionaryQueryResponse> {

    /**
     * 转换 Response，转换之后的数据直接返回给客户端
     *
     * @param dictionary 实体类
     * @return response
     */
    @Override
    default DictionaryQueryResponse transformToResponse(DictionaryBo dictionary) {
        DictionaryQueryResponse vo = new DictionaryQueryResponse();
        BeanUtils.copyProperties(dictionary, vo);
        return vo;
    }

    /**
     * 将请求 request 转换成 manager 的 query 对象
     *
     * @param request 请求参数
     * @return query 对象
     */
    @Override
    default PageRequest<DictionaryQuery> transformToQuery(PageRequest<DictionaryQueryRequest> request) {
        DictionaryQuery query = new DictionaryQuery();
        if (Objects.nonNull(request.getData())) {
            BeanUtil.copyProperties(request.getData(), query);
        }

        // 转换请求
        PageRequest<DictionaryQuery> pageRequest = new PageRequest<>();
        pageRequest.setPageNum(request.getPageNum());
        pageRequest.setPageSize(request.getPageSize());
        pageRequest.setData(query);
        return pageRequest;
    }

    /**
     * 将请求 request 转换成实体类，转换之后的数据保存到数据库中
     *
     * @param request 保存请求vo
     * @return 实体
     */
    @Override
    default DictionaryBo transformToEntity(DictionarySaveRequest request) {
        DictionaryBo entity = new DictionaryBo();
        BeanUtils.copyProperties(request, entity);
        return entity;
    }

    /**
     * 将上传的内容转换成实体类，转换之后的数据保存到数据库中
     *
     * @param importDtos 上传dto
     * @return 实体bo
     */
    default List<DictionaryBo> transformToEntities(List<DictionaryImportDto> importDtos) {
        List<DictionaryBo> resultList = new ArrayList<>();
        for (DictionaryImportDto importDto : importDtos) {
            DictionaryBo entity = new DictionaryBo();
            BeanUtils.copyProperties(importDto, entity);
            resultList.add(entity);
        }
        return resultList;
    }
}
